package cn.apthink.schedule;

import java.util.ArrayList;
import java.util.List;

import cn.apthink.utility.Util;
import lombok.Data;

@Data
public class SoluationHelper {
	private List<Soluation> soluations = new ArrayList<Soluation>();
	private int maxLength;

	public SoluationHelper(int maxLength) {
		super();
		this.maxLength = maxLength;
	}

	public void init() {
		soluations.clear();
	}

	public void add(Soluation soluation) {
		if (soluations.contains(soluation))
			return;
		soluations.add(soluation);
		// David：排序积分大时间小
		soluations.sort((a, b) -> {
			if (a.getScore() != b.getScore())
				return a.getScore() > b.getScore() ? -1 : 1;
			return a.getCreatetime().compareTo(b.getCreatetime());
		});
		if (soluations.size() > maxLength) {
			soluations.remove(soluations.size() - 1);
		}
	}

	public void add(List<Soluation> datas) {
		if (Util.isEmpty(datas))
			return;
		if (Util.isEmpty(soluations)) {
			soluations.addAll(datas);
			return;
		}
		long minScore = soluations.stream().map(Soluation::getScore).min((a, b) -> a.compareTo(b)).get();
		datas.forEach(x -> {
			if (x.getScore() >= minScore || soluations.size() < maxLength)
				add(x);
		});
	}

	public List<Soluation> topSoluations() {
		List<Soluation> result = new ArrayList<Soluation>();
		long maxScore = soluations.stream().map(Soluation::getScore).max((a, b) -> a.compareTo(b)).get();
		for (int i = 0, l = soluations.size(); i < l; i++) {
			Soluation soluation = soluations.get(i);
			if (maxScore == soluation.getScore())
				result.add(soluation);
		}
		return result;
	}

	public List<Soluation> tailSoluations() {
		List<Soluation> result = new ArrayList<Soluation>();
		long minScore = soluations.stream().map(Soluation::getScore).min((a, b) -> a.compareTo(b)).get();
		for (Soluation soluation : soluations) {
			if (minScore == soluation.getScore())
				result.add(soluation);
		}
		return result;
	}

	public static void log(List<Soluation> soluations) {
		soluations.forEach(x -> {
			System.out.println(x.toString());
		});
		System.out.println("Soluations size=" + soluations.size());
	}

	public static void logSimple(List<Soluation> soluations) {
		soluations.forEach(x -> {
			System.out.println(x.toSimple());
		});
		System.out.println("Soluations size=" + soluations.size());
	}
}
